/**
 *
 */
package co.fitstart.api.dao;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.demo2do.core.persistence.GenericDaoSupport;

import co.fitstart.entity.content.Article;
import co.fitstart.entity.content.Module;
import co.fitstart.entity.content.page.Webpage;

/**
 * @author downpour
 *
 */
@Repository("contentDaoSupport")
public class ContentDaoSupport {

    @Autowired
    private GenericDaoSupport genericDaoSupport;

    /**
     * Load all web pages and find by alias
     *
     * @param alias
     * @return
     */
    public Webpage getWebpage(String alias) {
        List<Webpage> webpages = genericDaoSupport.loadAll(Webpage.class);
        for(Webpage webpage : webpages) {
            if(webpage.matches(alias)) {
                return webpage;
            }
        }
        return null;
    }
    
    /**
     * Load module by id
     * 
     * @param id
     * @return
     */
    public Module getModule(Long id) {
        
        Module module = null;
        
        List<Module> modules = genericDaoSupport.loadAll(Module.class);
        
        for(Module temp : modules) {
            if(!temp.isDisabled() && temp.isDisplay() && temp.getId() == id) {
                module = temp;
            }
        }
        
        return module;
    }
    
    
    /**
     * Load all modules and filter by display
     *
     * @return
     */
    public List<Module> listModule() {
        List<Module> modules = genericDaoSupport.loadAll(Module.class);
        List<Module> result = new ArrayList<Module>();
        for(Module module : modules) {
            if(!module.isDisabled() && module.isDisplay()) {
                result.add(module);
            }
        }
        return result;
    }

    /**
     * Load all modules and find by alias
     *
     * @param alias
     * @return
     */
    public Module getModule(String alias) {
        List<Module> modules = genericDaoSupport.loadAll(Module.class);
        for(Module module : modules) {
            if(module.matches(alias)) {
                return module;
            }
        }
        return null;
    }

    /**
     * @param module
     * @return
     */
    @SuppressWarnings("unchecked")
    public List<Article> getHotArticleByModule(Module module) {
        String sentence = "SELECT articleModule.article FROM ArticleModule articleModule WHERE articleModule.module = :module AND serial > 100 AND articleModule.article.disabled = false ORDER BY serial ASC";
        return genericDaoSupport.searchForList(sentence, "module", module);
    }

}
